# search歌曲搜索、hot热门歌曲、soaring飙升歌曲、singer歌手排名
# 2t58表示的api地址：http://www.2t58.com
import base64
import requests
from lxml import etree
import time
import threading

def handOutApi(url,type,parameter:dict):
    """

    :param url: 2t58表示的api地址http://www.2t58.com
    :param type: 查询类型 search歌曲搜索、hot热门歌曲、soaring飙升歌曲、singer歌手排名
    :return:
    """
    if url=='2t58':
        # 热门歌曲列表查询
        if type=="hot":
            page = parameter.get("page",'1')
            data,err = api2t58.hot(page)
            return data,err
        # 热门歌曲单个查询
        if type=="hotpk":
            pk = parameter.get("pk",'')
            if pk =='':
                return None, 'pk不能为空'
            data,err = api2t58.musicDetail(pk)
            return data,err
        # 搜索歌曲列表搜索
        if type=="search":
            page = parameter.get("page",'1')
            name = parameter.get("name",'')
            if name=='':
                return None,'关键字不能为空'
            data,err = api2t58.search(name,page)
            return data,err
        # 新歌曲列表查询
        if type=="news":
            page = parameter.get("page",'1')
            data,err = api2t58.news(page)
            return data,err
        # 抖音热歌曲列表查询
        if type == "douyin":
            page = parameter.get("page", '1')
            data, err = api2t58.douyin(page)
            return data, err
    return None,'没有此代理地址'

class api2t58:

    url = "http://www.2t58.com"

    @classmethod
    def hot(cls,page):
        """
        hot热门歌曲
        :return:
        """
        # http://www.2t58.com/list/new/1.html
        url = cls.url+"/list/top/"+str(page)+".html"

        r = requests.get(url)
        if r.status_code == 202:
            print(r.content)
            return None,'查询失败'
        # print(r.text)
        html =  etree.HTML(r.text)

        # 判断是否存在下一页
        nextPage = html.xpath("//div[@class='page']/a[text()='下一页']/text()")

        # 判断是否存在上一页
        previousPage = html.xpath("//div[@class='page']/a[text()='上一页']/text()")

        # 查询歌单列表
        result = html.xpath("//div[@class='play_list']/ul/li")
        dataList = []
        # semaphore = threading.BoundedSemaphore(10)  # 限制线程最大数量
        # thread_list = []
        for index,itm in enumerate(result):

            # 歌曲的名称
            music_name = itm.xpath("//div[@class='play_list']/ul/li/div/a/text()")[index]

            # 歌曲id
            music_index = itm.xpath("//div[@class='play_list']/ul/li/div/a/@href")[index]
            # cls.hotDetail(index,sem,bbb)
            if '/video/' not in music_index:
                # print(music_index)
                music_id = music_index[6:][:-5]
                dataList.append({
                    "id":music_id,
                    "name":music_name,
                    "singer":'',
                    "url":'',
                    "lrcUrl":'',
                })
        #         # 开启多线程查询歌曲播放地址
        #         ts = threading.Thread(target=cls.hotThreading, args=(music_id, semaphore,dataList))
        #         thread_list.append(ts)
        # for thread in thread_list:
        #     thread.start()
        #
        # for thread in thread_list:
        #     thread.join()
        # print(dataList)
        data = {}
        data['data'] = dataList
        data['nextPage'] = True if len(nextPage)>0 else False
        data['previousPage'] = True if len(previousPage)>0 else False

        return data,None

    @classmethod
    def musicDetail(cls,id):
        url = cls.url + "/js/play.php"
        Referer = cls.url + "/song/" + id + ".html"
        data = requests.post(url, data={"id": id, "type": "music"}, headers={"Referer": Referer})
        if data.status_code != 200:
            return None,'歌曲播放失败'
        if data.json()['msg'] != 1:
            return None, '歌曲播放异常'
        detail = {}
        detail['url'] = data.json()['url']
        detail['name'] = data.json()['title']
        detail['id'] = data.json()['lkid']
        detail['lrcUrl'] = "https://api.44h4.com/lc.php?cid=" + str(data.json()['lkid'])
        detail['singer'] = ''
        return detail,None

    @classmethod
    def hotThreading(cls,id,semaphore,dataList:list):
        """
        热门歌曲详情查询----------------多线程查询歌曲详情，暂时未使用
        :param id:
        :param semaphore:
        :param dataList:
        :return:
        """
        semaphore.acquire()

        url = cls.url + "/js/play.php"
        Referer = cls.url + "/song/"+id+".html"
        data = requests.post(url, data={"id": id, "type": "music"},headers={"Referer":Referer})
        if data.status_code !=200:
            return
        if data.json()['msg']!=1:
            return
        detail = {}
        detail['url'] = data.json()['url']
        detail['name'] = data.json()['title']
        detail['id'] = data.json()['lkid']
        detail['lrcUrl'] ="https://api.44h4.com/lc.php?cid="+ str(data.json()['lkid'])
        detail['singer'] = ''
        dataList.append(detail)
        semaphore.release()

    @classmethod
    def search(cls,name,page):
        url = cls.url + "/so/"+ name+'/' + str(page) + ".html"
        print(url)
        r = requests.get(url)
        if r.status_code == 202:
            print(r.content)
            return None, '查询失败'
        print(r.text)
        html = etree.HTML(r.text)
        # 判断是否存在下一页
        nextPage = html.xpath("//div[@class='page']/a[text()='下一页']/text()")

        # 判断是否存在上一页
        previousPage = html.xpath("//div[@class='page']/a[text()='上一页']/text()")

        # 查询歌单列表
        result = html.xpath("//div[@class='play_list']/ul/li/div[@class='name']")
        dataList = []
        # semaphore = threading.BoundedSemaphore(10)  # 限制线程最大数量
        # thread_list = []
        for index, itm in enumerate(result):

            # 歌曲的名称
            music_name = itm.xpath("//div[@class='play_list']/ul/li/div[@class='name']/a/text()")[index]

            # 歌曲id
            music_index = itm.xpath("//div[@class='play_list']/ul/li/div[@class='name']/a/@href")[index]
            # print(music_index)
            music_id = music_index[6:][:-5]
            dataList.append({
                "id": music_id,
                "name": music_name,
                "singer": '',
                "url": '',
                "lrcUrl": '',
            })
        data = {}
        # print(dataList)
        data['data'] = dataList
        data['nextPage'] = True if len(nextPage) > 0 else False
        data['previousPage'] = True if len(previousPage) > 0 else False
        return data,None

    @classmethod
    def news(cls,page):
        """
        hot新歌曲
        :return:
        """
        # http://www.2t58.com/list/new/1.html
        url = cls.url+"/list/news/"+str(page)+".html"

        r = requests.get(url)
        if r.status_code == 202:
            print(r.content)
            return None,'查询失败'
        # print(r.text)
        html =  etree.HTML(r.text)

        # 判断是否存在下一页
        nextPage = html.xpath("//div[@class='page']/a[text()='下一页']/text()")

        # 判断是否存在上一页
        previousPage = html.xpath("//div[@class='page']/a[text()='上一页']/text()")

        # 查询歌单列表
        result = html.xpath("//div[@class='play_list']/ul/li")
        dataList = []
        # semaphore = threading.BoundedSemaphore(10)  # 限制线程最大数量
        # thread_list = []
        for index,itm in enumerate(result):

            # 歌曲的名称
            music_name = itm.xpath("//div[@class='play_list']/ul/li/div/a/text()")[index]

            # 歌曲id
            music_index = itm.xpath("//div[@class='play_list']/ul/li/div/a/@href")[index]
            # cls.hotDetail(index,sem,bbb)
            if '/video/' not in music_index:
                # print(music_index)
                music_id = music_index[6:][:-5]
                dataList.append({
                    "id":music_id,
                    "name":music_name,
                    "singer":'',
                    "url":'',
                    "lrcUrl":'',
                })
        #         # 开启多线程查询歌曲播放地址
        #         ts = threading.Thread(target=cls.hotThreading, args=(music_id, semaphore,dataList))
        #         thread_list.append(ts)
        # for thread in thread_list:
        #     thread.start()
        #
        # for thread in thread_list:
        #     thread.join()
        # print(dataList)
        data = {}
        data['data'] = dataList
        data['nextPage'] = True if len(nextPage)>0 else False
        data['previousPage'] = True if len(previousPage)>0 else False

        return data,None

    @classmethod
    def douyin(cls, page):
        """
        hot新歌曲
        :return:
        """
        # http://www.2t58.com/list/new/1.html
        url = cls.url + "/list/douyin/" + str(page) + ".html"

        r = requests.get(url)
        if r.status_code == 202:
            print(r.content)
            return None, '查询失败'
        # print(r.text)
        html = etree.HTML(r.text)

        # 判断是否存在下一页
        nextPage = html.xpath("//div[@class='page']/a[text()='下一页']/text()")

        # 判断是否存在上一页
        previousPage = html.xpath("//div[@class='page']/a[text()='上一页']/text()")

        # 查询歌单列表
        result = html.xpath("//div[@class='play_list']/ul/li")
        dataList = []
        # semaphore = threading.BoundedSemaphore(10)  # 限制线程最大数量
        # thread_list = []
        for index, itm in enumerate(result):

            # 歌曲的名称
            music_name = itm.xpath("//div[@class='play_list']/ul/li/div/a/text()")[index]

            # 歌曲id
            music_index = itm.xpath("//div[@class='play_list']/ul/li/div/a/@href")[index]
            # cls.hotDetail(index,sem,bbb)
            if '/video/' not in music_index:
                # print(music_index)
                music_id = music_index[6:][:-5]
                dataList.append({
                    "id": music_id,
                    "name": music_name,
                    "singer": '',
                    "url": '',
                    "lrcUrl": '',
                })
        # # 开启多线程查询歌曲播放地址
        #         ts = threading.Thread(target=cls.hotThreading, args=(music_id, semaphore,dataList))
        #         thread_list.append(ts)
        # for thread in thread_list:
        #     thread.start()
        #
        # for thread in thread_list:
        #     thread.join()
        # print(dataList)
        data = {}
        data['data'] = dataList
        data['nextPage'] = True if len(nextPage) > 0 else False
        data['previousPage'] = True if len(previousPage) > 0 else False

        return data, None

    def soaring(self):
        """
        soaring飙升歌曲
        :return:
        """

    def singer(self):
        """
        singer歌手排名
        :return:
        """
# 热门歌曲查询
# aaa = handOutApi("2t58","hot",{"page":'2'})

# 搜索歌曲查询
# aaa = handOutApi("2t58","search",{"page":'1','name':'薛之谦'})

# aaa = handOutApi("2t58","news",{"page":'1'})
# print(aaa)
# /song/bWhzZGRzY3ht.html
# /video/bWhzZGRzY3ht.html
# id="bWhzZGRzY3ht"
# url = "http://www.2t58.com" + "/js/play.php"
# Referer = "http://www.2t58.com" + "/song/"+id+".html"
# aaa = requests.post(url, data={"id": id, "type": "music"},headers={"Referer":Referer})
# print('xiangqing')
# print(aaa.json())
# {'msg': 1, 'lkid': 289339642, 'title': '欧阳娜娜 - Mama Said', 'pic': 'https://img1.kuwo.cn/star/albumcover/300/74/98/1901823462.jpg', 'url': 'http://down.2t58.com/mp3/289339642.mp3'}
# bWhzaGtreHdt

# # https://api.44h4.com/lc.php?cid=289800412
#
# aaa = requests.get("http://www.2t58.com/js/play.php",json={"id":"bWhzaGtreHdt","type":"music"})
# print("aa")
# print(aaa.status_code)
# print(aaa.text)

# import time
# import threading
#
# sem = threading.Semaphore(10)  # 限制线程最大数量
#
#
# def function(c, d):
#     with sem:  # 锁定线程的最大数量
#         print(str(c) + ' ' + str(d))
#         time.sleep(2)
#         print('-----------------')
#
#
# for c in range(1, 50):
#     ts = threading.Thread(target=function, args=(c, c))
#     ts.start()
